package cn.wolfcode.crm.authc;

import cn.wolfcode.crm.util.JSONResult;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
import org.springframework.stereotype.Component;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import java.io.IOException;

@Component
public class MyformAuthenticationFilter extends FormAuthenticationFilter{
    @Override
    protected boolean onLoginSuccess(AuthenticationToken token, Subject subject, ServletRequest request, ServletResponse response) throws Exception {
       //设置响应的信息是json格式的数据
        response.setContentType("application/json;charset=utf-8");
        JSONResult result = new JSONResult();
        response.getWriter().print(new ObjectMapper().writeValueAsString(result));
        return false;
    }


    //重写登入失败
    @Override
    protected boolean onLoginFailure(AuthenticationToken token, AuthenticationException e, ServletRequest request, ServletResponse response) {
        //设置响应的信息是json格式的数据
        response.setContentType("application/json;charset=utf-8");
        //设置登入失败信息
        String msg ="登录失败,请联系管理员";
        if (e instanceof UnknownAccountException) {
            msg ="用户名不正确";
        }
        else if (e instanceof IncorrectCredentialsException) {
            msg ="密码不正确";
        }
        JSONResult result = new JSONResult();
        result.mark(msg);
        try {
            response.getWriter().print(new ObjectMapper().writeValueAsString(result));
        } catch (IOException e1) {
            e1.printStackTrace();
        }

        return false;
    }
}
